package top.igotcha.eduservice.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import top.igotcha.eduservice.client.VodClient;
import top.igotcha.eduservice.entity.EduVideo;
import top.igotcha.eduservice.mapper.EduVideoMapper;
import top.igotcha.eduservice.service.EduVideoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import top.igotcha.commonutils.exception.GuliException;
import top.igotcha.commonutils.utils.R;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 课程视频 服务实现类
 * </p>
 *
 * @author Gotcha
 * @since 2021-08-06
 */
@Service
public class EduVideoServiceImpl extends ServiceImpl<EduVideoMapper, EduVideo> implements EduVideoService {

    @Autowired
    VodClient vodClient;

    @Override
    public void removeVideoByCourseId(String courseId) {
        List<EduVideo> eduVideoList = baseMapper.selectList(new QueryWrapper<EduVideo>().eq("course_id", courseId).select("video_source_id"));
        List<String> videoSourceIds = new ArrayList<>();
        for (EduVideo eduVideo : eduVideoList) {
            String videoSourceId = eduVideo.getVideoSourceId();
            if(!StringUtils.isEmpty(videoSourceId)){
                videoSourceIds.add(videoSourceId);
            }
        }
        if (videoSourceIds.size()>0){
            R r = vodClient.removeBatchAliYunVideo(videoSourceIds);
            if(r.getCode()==20001){
                throw new GuliException(20001,"批量删除视频失败，触发熔断器");
            }
        }

        baseMapper.delete(new QueryWrapper<EduVideo>().eq("course_id",courseId));
    }

    @Override
    public R removeFromAliYun(String videoId) {
        R r = vodClient.removeAliYunVideo(videoId);
        return r;
    }
}
